'use strict'
const path = require('path')
const VueFilenameInjector = require('@d2-projects/vue-filename-injector')
const config = require('./src/config')
const TerserPlugin = require('terser-webpack-plugin')
const CompressionPlugin = require('compression-webpack-plugin')
const glob = require('glob')
const modules = glob.sync(resolve('src') + '/modules/*/index.vue')

function resolve (dir) {
  return path.join(__dirname, dir)
}
const name = config.title || 'Fawkes' // page title
// If your port is set to 80,
// use administrator privileges to execute the command line.
// For Example, Mac: sudo npm run
const port = 9528 // dev port
// All configuration item explanations can be find in https://cli.vuejs.org/config/
module.exports = {
  /**
   * You will need to set publicPath if you plan to deploy your site under a sub path,
   * for Example GitHub Pages. If you plan to deploy your site to https://foo.github.io/bar/,
   * then publicPath should be set to "/bar/".
   * In most cases please use '/' !!!
   * Detail: https://cli.vuejs.org/config/#publicpath
   */
  publicPath: './',
  outputDir: 'dist',
  assetsDir: '',
  lintOnSave: false,
  // lintOnSave: process.env.NODE_ENV === 'development',
  productionSourceMap: false,
  devServer: {
    headers: { 'Access-Control-Allow-Origin': '*' },
    port: port,
    open: false,
    overlay: {
      warnings: false,
      errors: true
    },
    proxy: config.proxy
    // after: require('./mock/mock-server.js')
  },
  configureWebpack: {


    output: {
      // 微应用的包名，这里与主应用中注册的微应用名称一致
      library: `${config.appName}`,
      // 将你的 library 暴露为所有的模块定义下都可运行的方式
      libraryTarget: 'umd',
      // 按需加载相关，设置为 webpackJsonp_VueMicroApp 即可
      jsonpFunction: `webpackJsonp_${config.appName}`
    },
    // provide the app's title in webpack's name field, so that
    // it can be accessed in index.html to inject the correct title.
    name: name,
    devtool: process.env.NODE_ENV === 'production' ? '' : 'eval-source-map',
    resolve: {
      alias: {
        '@': resolve('src'),
        'bn.js': path.resolve(process.cwd(), 'node_modules', 'bn.js'),
        sortablejs: path.resolve(process.cwd(), 'node_modules', 'sortablejs'),
        zrender: path.resolve(process.cwd(), 'node_modules', 'zrender')
      }
    },
    module: {
      rules: [
        {
          test: /\.js$/,
          use: ['thread-loader']
        }
      ]
    },
    optimization: {
      minimizer: [
        new TerserPlugin({
          //采用多进程打包
          parallel: 4,
          terserOptions: {
            compress: {
              // 去除debug、console
              warnings: false,
              drop_debugger: false,
              drop_console: false
            }
          }
        })
      ]
    }
  },
  chainWebpack (config) {
    // config
    //   .plugin('webpack-bundle-analyzer')
    //   .use(require('webpack-bundle-analyzer').BundleAnalyzerPlugin)
    //   .end()
    config.plugins.delete('preload') // TODO: need test
    config.plugins.delete('prefetch') // TODO: need test
    // set svg-sprite-loader
    config.module
      .rule('svg')
      .exclude.add(resolve('src/assets/svg'))
      .end()
    config.module
      .rule('icons')
      .test(/\.svg$/)
      .include.add(resolve('src/assets/svg')) //处理svg目录
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]'
      })
      .end()

    // style - loader覆盖默认loader实现样式动态加载可控
    /**
     * const css = config.module.rule('css').toConfig()
     * const useable = { ...css.oneOf[3], test: /index_(.+)\.css$/i }
     * useable.use = [...useable.use]
     * useable.use[0] = { loader: 'style-loader', options: { injectType: 'lazySingletonStyleTag' } }
     * config.module.rule('css').merge({ oneOf: [useable] })
     */

    // set preserveWhitespace
    config.module
      .rule('vue')
      .use('vue-loader')
      .loader('vue-loader')
      .tap((options) => {
        options.compilerOptions.preserveWhitespace = true
        return options
      })
      .end()

    VueFilenameInjector(config, {
      propName: '__source' // default
    })

    config.when(process.env.NODE_ENV !== 'development', (config) => {
      config
        .plugin('compressionPlugin')
        .use(
          new CompressionPlugin({
            test: /\.js$|\.html$|\.css/,
            threshold: 10240,
            deleteOriginalAssets: true
          })
        )
        .end()
      // config
      //   .plugin('ScriptExtHtmlWebpackPlugin')
      //   .after('html')
      //   .use('script-ext-html-webpack-plugin', [{
      //     // `runtime` must same as runtimeChunk name. default is `runtime`
      //     inline: /runtime\..*\.js$/
      //   }])
      //   .end()
      let group = {
        chunks: 'all',
        cacheGroups: {
          vendor: {
            name: 'chunk-vendor',
            test: /[\\/]node_modules[\\/]/,
            priority: 10,
            chunks: 'initial' // only package third parties that are initially dependent
          },
          fawkes: {
            name: 'chunk-fawkes', // split elementUI into a single package
            priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app
            test: /[\\/]node_modules[\\/]_?fawkes-lib(.*)/,
            chunks: 'initial'
          },
          lang: {
            name: 'chunk-lang', // 本地国际化合并
            priority: 20,
            test: /[\\/]src(.*)[\\/]lang.js/
          },
          commons: {
            name: 'chunk-commons',
            test: resolve('src'), // can customize your rules
            minChunks: 2, //  minimum common number
            priority: 30,
            chunks: 'initial',
            reuseExistingChunk: true
          }
        }
      }
      modules.forEach((module) => {
        let name = module.match(/(?<=modules\/)[\d\D]+(?=\/index.vue)/)
        group.cacheGroups[name] = {
          name: `chunk-${name}`,
          priority: 20,
          test: resolve(`/src/modules/${name}`)
        }
      })
      config.optimization.splitChunks(group)

      console.log(config.optimization.splitChunks)
      config.optimization.runtimeChunk('single')
      config.optimization.minimize(true) // 代码压缩
    })
  }
}
